from apscheduler.triggers.cron import CronTrigger
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from starlette.requests import Request
from plugin.backgrouds import scheduler
from plugin.database import get_db
from sqlmodel import Session, select
from models.task import Task

task_router = APIRouter(prefix="/task", tags=["任务接口"])


class TaskAdd(BaseModel):
    title: str
    cron: str
    kwargs: dict


def create_task(kwargs):
    try:
        print(f"python {kwargs}")
        res = {
            "code": 0,
            "message": "success"}
    except Exception as e:
        res = {
            "code": 0,
            "message": "failed",
            "data": [e]}
    return res


@task_router.get("/", summary="获取所有任务")
def get_tasks_list(limit: int = 10, skip: int = 0):
    jobs = scheduler.get_jobs()
    """获取所有任务"""
    res = {
        "code": 0,
        "message": "success",
        "data": [job.id for job in jobs[limit * skip:limit * skip + limit]]}
    return res


@task_router.get("/{task_id}", summary="获取任务详情")
def get_tasks_detail(task_id: str, db: Session = Depends(get_db)):
    query_code = select(Task).where(Task.id == task_id)
    results = db.exec(query_code).all()
    """获取任务详情"""
    res = {
        "code": 0,
        "message": "success",
        "data": [{
            "id": results[0].id,
            "title": results[0].title,
            "next_run_time": results[0].next_run_time,
            "trigger": results[0].trigger,
            "kwargs": results[0].kwargs
        }]}
    return res


@task_router.post("/", summary="新增任务")
def add_tasks(request: Request, task: TaskAdd):
    job = scheduler.add_job(create_task,
                            trigger=CronTrigger.from_crontab(task.cron),
                            kwargs={'kwargs': task.kwargs},
                            name=task.title)
    """新增任务"""
    res = {
        "code": 200,
        "message": "success",
        "data": {"job_id": job.id}}
    return res


@task_router.put("/{task_id}", summary="修改任务")
def put_tasks(request: Request, task_id: str, task: TaskAdd):
    scheduler.remove_job(task_id)
    job = scheduler.add_job(create_task,
                            trigger=CronTrigger.from_crontab(task.cron),
                            kwargs={'kwargs': task.kwargs},
                            id=task_id,
                            name=task.title)
    res = {
        "code": 200,
        "message": "success",
        "data": {"job_id": job.id}}
    return res


@task_router.delete("/{task_id}", summary="删除任务")
def del_tasks(task_id: str, request: Request):
    """删除任务"""
    scheduler.remove_job(task_id)
    return {'task_id': task_id, 'message': '任务已删除'}
